package com.cloud.lan.pub.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloud.lan.dao.LanManageUserMapper;
import com.cloud.lan.dao.LanUserWxMapper;
import com.cloud.lan.dao.SysWhiteListMapper;
import com.cloud.lan.entity.base.BaseResponse;
import com.cloud.lan.entity.model.dataobject.LanManageUserDO;
import com.cloud.lan.entity.model.dataobject.SysWhiteListDO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import static com.cloud.lan.entity.utils.ConstantInterface.Enum.ConstantNumber.ZERO;

/**
 * Spring boot 拦截器 验证所有请求权限
 * @author ErKang
 * @date Created in 2021/12/9 02:55
 * @title RequestInterceptor.java
 * Department: Product development
 */
@Slf4j
@Component
public class RequestInterceptor extends HandlerInterceptorAdapter {

    @Value("${lan.system.switch:#{1}}")
    private static int SWITCH = 1;

    @Autowired
    SysWhiteListMapper sysWhiteListMapper;
    @Autowired
    LanUserWxMapper lanUserWxMapper;
    @Autowired
    LanManageUserMapper lanManageUserMapper;

    private void responseNoPerm(HttpServletRequest request, HttpServletResponse response) {
        try {
            PrintWriter out = null;
            response.setContentType("application/json;charset=UTF-8");
            out = response.getWriter();
            out.print(JSONUtil.parseObj(BaseResponse.error()));
            out.flush();
        } catch (IOException e) {
            log.error("#系统异常 - {}", e.getMessage());
        }
    }

    private void responseNoToken(HttpServletRequest request, HttpServletResponse response) {
        try {
            PrintWriter out = null;
            response.setContentType("application/json;charset=UTF-8");
            out = response.getWriter();
            out.print(JSONUtil.parseObj(BaseResponse.errorNoToken()));
            out.flush();
        } catch (IOException e) {
            log.error("#系统异常 - {}", e.getMessage());
        }
    }

    private void systemSwitchOut(HttpServletRequest request, HttpServletResponse response) {
        try {
            PrintWriter out = null;
            response.setContentType("application/json;charset=UTF-8");
            out = response.getWriter();
            out.print("店铺升级，精彩稍后继续....");
            out.flush();
        } catch (IOException e) {
            log.error("#系统异常 - {}", e.getMessage());
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        try {
            if (SWITCH == 0) {
                return true;
            }
            //拦截器 开关
            String requestUri = request.getRequestURI();
            //检查 url白名单信息表
            LambdaQueryWrapper<SysWhiteListDO> wqw = new LambdaQueryWrapper<>();
            wqw.eq(SysWhiteListDO::getUrl, requestUri);
            String token = request.getHeader("token");
            if (StrUtil.isEmpty(token)) {
                token = request.getParameter("token");
            }
            log.info("#用户 token ： {}", token);
            request.setAttribute("token", token);
            if (sysWhiteListMapper.selectCount(wqw) > 0) {
                log.info("# 触发白名单 直接通过 requestUri： {}", requestUri);
                return true;
            }

            if (StrUtil.isEmpty(token) || StrUtil.isNullOrUndefined(token)) {
                this.responseNoToken(request, response);
                return false;
            }

            // 运营系统拦截器
            LambdaQueryWrapper<LanManageUserDO> mqw = new LambdaQueryWrapper<>();
            mqw.eq(LanManageUserDO::getToken, token).eq(LanManageUserDO::getUserStatus, ZERO.getKey());
            if (lanManageUserMapper.selectCount(mqw).equals(ZERO.getKey())) {
                this.responseNoToken(request, response);
                return false;
            }

        } catch (Exception e) {
            log.error("# 拦截器异常 - {}", e.getMessage());
        }
        return true;
    }
}
